<template>
  <div class="row full-height">
    <q-card class="col-2 text-center">
      <q-card>
        <q-item>
          <q-item-section avatar>
            <q-avatar>
              <img :src="user.imageUrl" />
            </q-avatar>
          </q-item-section>
          <q-item-section>
            <q-item-label>{{ user.username }}</q-item-label>
          </q-item-section>
          <q-item-section class="col-5">
            <q-item-label>{{ userDetail.session }}级学生</q-item-label>
          </q-item-section>
        </q-item>
      </q-card>
      <q-separator inset />
      <q-tabs v-model="tabOption" vertical>
        <q-tab name="action1" label="具体信息" />
        <q-tab name="action2" label="收藏课程" />
        <q-tab name="action3" label="考研自评" />
        <q-tab name="action4" label="社区交流" @click="getPost" />
      </q-tabs>
    </q-card>
    <q-card class="col-10">
      <h4>距离步入考场还剩：</h4>
      <flip-clock />
      <q-separator inset />
      <q-dialog v-model="avatar" backdrop-filter="blur(4px)">
        <q-card>
          <q-card-section>
            <div class="text-h6">选择头像</div>
          </q-card-section>

          <q-separator />

          <q-card-section
            style="max-height: 50vh"
            class="scroll row q-col-gutter-y-md"
          >
            <a
              v-for="(url, index) in avatarlist"
              :key="index"
              class="flex col-6 justify-center"
              @click.prevent="selected = url"
            >
              <q-avatar :class="selected == url ? 'shadow-4 bordered' : ''">
                <q-img :src="url"></q-img>
              </q-avatar>
            </a>
          </q-card-section>

          <q-separator />
          <q-card-actions align="right">
            <p>已选头像：</p>
            <q-avatar>
              <q-img :src="selected" />
            </q-avatar>
            <q-btn v-close-popup flat label="取消" color="primary" />
            <q-btn
              v-close-popup
              flat
              label="提交"
              color="primary"
              @click="editAvatar"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
      <q-tab-panels v-model="tabOption" animated>
        <q-tab-panel name="action1">
          <q-expansion-item class="shadow-1">
            <template #header>
              <h6>基本信息</h6>
            </template>
            <q-list class="q-pl-md text-body1">
              <q-item class="row items-center">
                头像:
                <q-avatar rounded class="q-mx-md">
                  <q-tooltip>当前头像</q-tooltip>
                  <q-img :src="user.imageUrl" />
                </q-avatar>
                <q-btn bordered label="挑选头像" @click="getAvatarList()"
                  ><q-tooltip> 目前只支持系统内头像 </q-tooltip></q-btn
                >
              </q-item>
              <q-item class="row items-center">
                昵称:
                <q-input v-model="user.username" class="q-mx-md"></q-input>
              </q-item>
              <q-item class="row items-center">
                性别:
                <q-input v-model="user.gender" class="q-mx-md"></q-input>
              </q-item>
              <q-item class="row items-center">
                <q-btn> 编辑完成 </q-btn>
              </q-item>
            </q-list>
          </q-expansion-item>
          <q-expansion-item class="shadow-1">
            <template #header>
              <h6>学习信息</h6>
            </template>
            <q-list style="padding-left: 3rem; font-size: larger">
              <q-item class="row items-center">
                学年:
                <q-input v-model="userDetail.session" class="q-mx-md"></q-input>
              </q-item>
              <q-item class="row items-center">
                目标学校:
                <q-input
                  v-model="userDetail.schoolName"
                  class="q-mx-md"
                  debounce="1000"
                ></q-input>
              </q-item>
              <q-item class="row items-center">
                目标学科:
                <q-select
                  v-model="userDetail.majorName"
                  :options="schoolmajorlist"
                  @filter="getMajor"
                ></q-select>
              </q-item>
              <q-item class="row items-center">
                <q-btn @click="editMajor"> 编辑完成 </q-btn>
              </q-item>
            </q-list>
          </q-expansion-item>
        </q-tab-panel>
        <q-tab-panel name="action2">
          <h6>课程收藏夹</h6>
          <q-card>
            <q-carousel
              ref="carousel"
              v-model="slide"
              infinite
              transition-prev="scale"
              transition-next="scale"
              swipeable
              animated
              control-color="black"
              navigation
              padding
              arrows
            >
              <q-carousel-slide
                v-for="(item, index) in favCourses"
                :key="index"
                :name="'class' + index"
                class="flex flex-center"
              >
                <a class="full-height" style="width: 600px" :href="item.url">
                  <q-img
                    :src="imgUrlBase + item.imgUrl"
                    height="100%"
                    fit="contain"
                  >
                    <div class="absolute-bottom text-subtitle2 text-center">
                      {{ item.name }}
                    </div>
                  </q-img>
                </a>
              </q-carousel-slide>
            </q-carousel>
          </q-card>
        </q-tab-panel>
        <q-tab-panel name="action3">
          <q-banner v-if="user.score != 0" class="text-h6">
            目前成绩为
            <span class="text-weight-bolder" style="font-size: 18px">
              {{ user.score }}
            </span>
            ,于目前学校预计排名为
            <span class="text-weight-bolder" style="font-size: 18px">
              {{ ranking }}
            </span>
            , {{ comment }}
          </q-banner>
          <q-banner v-else class="text-h6"> 还没提交成绩，快点提交吧 </q-banner>
          <div class="flex">
            <q-input
              v-model="inputScore"
              type="number"
              label="输入成绩"
            ></q-input>
            <q-file
              v-model.lazy="file"
              label="请选择成绩图片"
              accept="image/*"
              filled
              bottom-slots
              counter
              class="col-grow"
              :multiple="false"
            >
              <template #prepend>
                <q-icon name="cloud_upload" @click.stop.prevent />
              </template>
              <template #append>
                <q-icon
                  name="close"
                  class="cursor-pointer"
                  @click.stop.prevent="file = null"
                >
                  <q-tooltip> 清空 </q-tooltip>
                </q-icon>
                <q-icon
                  name="send"
                  class="cursor-pointer q-ml-md"
                  @click.stop.prevent="sendFile"
                >
                  <q-tooltip> 发送 </q-tooltip>
                </q-icon>
              </template>
              <template #hint>
                上传图片需为真实成绩，后台会对图片进行校验
              </template>
            </q-file>
          </div>

          <q-img :src="fileURL" class="preview"></q-img>
        </q-tab-panel>
        <q-tab-panel name="action4">
          <q-expansion-item
            label="最近发送的帖子"
            default-opened
            expand-separator
          >
            <q-card v-if="hotpost != null" bordered>
              <q-card-section class="flex justify-between">
                <div>
                  <div class="text-h6">{{ hotpost.title }}</div>
                  <div class="text-subtitle2">
                    {{ hotpost.postdate.substring(0, 10) }}
                  </div>
                </div>
                <div class="row">
                  <q-chip icon="thumb_up">{{ hotpost.like }}</q-chip>
                </div>
              </q-card-section>
              <q-separator inset></q-separator>
              <q-card-section>
                {{ hotpost.content }}
              </q-card-section>
            </q-card>
            <q-banner v-else class="text-h6 text-weight-bold">
              <a @click="router.push('post')">暂时没有发帖，点击去发帖吧</a>
            </q-banner>
          </q-expansion-item>
          <q-separator />
          <q-expansion-item label="最近消息" expand-separator>
            <q-list>
              <q-item v-if="messagelist.length <= 0">已经没有更多信息了</q-item>
              <q-slide-item
                v-for="(item, index) in messagelist"
                :key="index"
                @right="right"
                @slide="i = index"
              >
                <template #right>
                  <q-icon name="delete" />
                </template>
                <q-item v-ripple>
                  <q-item-section>
                    <q-item-label
                      >{{ item.user }} &nbsp; {{ item.action }}了你<em
                        >"&emsp;
                        {{
                          item.post
                            ? "帖子标题：" + item.post
                            : "信息：" + item.msg
                        }}"</em
                      ></q-item-label
                    >
                    <q-item-label caption>2024/5/20 21:30:12</q-item-label>
                  </q-item-section>
                </q-item>
              </q-slide-item>
            </q-list>
          </q-expansion-item>
        </q-tab-panel>
      </q-tab-panels>
    </q-card>
  </div>
</template>
<script setup>
import { messagelist } from "src/js/messagelist";
import { useQuasar } from "quasar";
import { post, multipartPost, get } from "src/js/fetch";
import { baseurl, logged, lorem } from "src/js/global";
import { onMounted, ref, computed } from "vue";
import { useRouter } from "vue-router";
import { imgUrlBase } from "src/js/global";
import flipClock from "src/components/flip-clock.vue";
const schoolmajorlist = ref([]);
const tabOption = ref("action1");
const file = ref(null);
const fileURL = computed(() => {
  return file.value == null ? "" : URL.createObjectURL(file.value);
});
const avatar = ref(false);
const selected = ref("");
const avatarlist = ref([]);
const ranking = ref(5);
const comment = computed(() => {
  if (ranking.value <= 3) {
    return "成绩斐然，成功就在眼前";
  } else if (ranking.value <= 10) {
    return "做的不错，还需继续努力";
  } else {
    return "风险较大，需要更加用心";
  }
});
const favCourses = ref([]);
const user = ref({
  username: "示例用户",
  gender: "男",
  score: 0,
  imageUrl: "https://cdn.quasar.dev/img/boy-avatar.png",
});
const userDetail = ref({
  schoolName: "",
  majorName: "",
  session: 0,
});
const inputScore = ref("0");
const slide = ref("class1");
const $q = useQuasar();

let i = 0;

function right({ reset }) {
  messagelist.value.splice(i, 1);
  reset();
}

function sendFile() {
  const url = new URL(baseurl + "user/score");
  url.searchParams.set("score", inputScore.value);
  const formData = new FormData();
  // const blob = new Blob([file.value], { type: "png/jpeg/jpg" });
  // formData.append("file", blob);
  formData.append("file", file.value);
  multipartPost(url, formData).then((res) => {
    console.log(res);
    if (res.success)
      $q.notify({
        message: res.data,
        type: "positive",
        position: "center",
      });
    else
      $q.notify({
        message: res.errorMsg,
        type: "positive",
        position: "center",
      });
  });
  getUserDetail();
  getFavCourse();
  getRanking();
}

function getUserDetail() {
  const url = baseurl + "user/detail";
  post(url, null).then((res) => {
    if (res.success) {
      console.log(res);
      user.value.username = res.data.userName;
      user.value.imageUrl = res.data.imgUrl;
      userDetail.value.majorName = res.data.majorName;
      userDetail.value.schoolName = res.data.schoolName;
      res.data.session
        ? (userDetail.value.session = res.data.session)
        : (userDetail.value.session = 2025);
      if (res.data.score) user.value.score = res.data.score;
    }
  });
}

const router = useRouter();
onMounted(() => {
  logged.value = sessionStorage.getItem("logged");
  if (!logged.value) router.replace("/login");
  else {
    getUserDetail();
    getRanking();
    getFavCourse();
  }
});
function getRanking() {
  if (user.value.score == 0) {
    return;
  }
  const url = new URL(baseurl + "user/rank");
  get(url).then((res) => {
    ranking.value = res.data;
  });
}
function getFavCourse() {
  const url = new URL(baseurl + "user/favorites");
  url.searchParams.set("current", 1);
  url.searchParams.set("size", 10);
  get(url).then((res) => {
    favCourses.value = res.data;
  });
}
function getMajor(val, update, abort) {
  // 测试时静态数据使用
  // if (schoolmajorlist.value != null) {
  //   majorlist.value.forEach((value) => {
  //     schoolmajorlist.value.push(value.name);
  //   });
  //   update();
  // }

  update();
  if (!schoolmajorlist.value != null) {
    const url = new URL(baseurl + "major/" + userDetail.value.schoolName);
    get(url).then((res) => {
      console.log("major", res);
      if (res.success) {
        res.data.forEach((value) => {
          schoolmajorlist.value.push(value.name);
        });
      }
    });
  }
}
function editMajor() {
  const url = new URL(baseurl + "user/detail/set");
  url.searchParams.set("schoolName", userDetail.value.schoolName);
  url.searchParams.set("majorName", userDetail.value.majorName);
  url.searchParams.set("session", userDetail.value.session);
  post(url).then((res) => {
    console.log(res);
    if (res.success)
      $q.notify({
        message: res.data,
        type: "positive",
        position: "center",
      });
    else
      $q.notify({
        message: res.errorMsg,
        type: "positive",
        position: "center",
      });
    getUserDetail();
  });
}

function getAvatarList() {
  avatar.value = !avatar.value;
  if (avatarlist.value.length <= 0) {
    const url = new URL(baseurl + "user/img/list");
    get(url).then((res) => {
      avatarlist.value = res.data;
    });
  }
}
function editAvatar() {
  const url = new URL(baseurl + "user/img/set");
  url.searchParams.set("imgUrl", selected.value);
  post(url).then((res) => {
    console.log(res);
    if (res.success)
      $q.notify({
        message: res.data,
        type: "positive",
        position: "center",
      });
    else
      $q.notify({
        message: res.errorMsg,
        type: "positive",
        position: "center",
      });
    getUserDetail();
  });
}

const hotpost = ref(null);
function getPost() {
  const url = new URL(baseurl + "post/myhot");
  get(url).then((res) => {
    if (res.success) {
      console.log(res);
      hotpost.value = res.data;
    } else {
      console.log(res);
    }
  });
}
</script>
<style scoped></style>
